package com.kg.module.jtnc.hhrdagl.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kg.component.file.FilePathConfig;
import com.kg.component.office.ExcelReadUtils;
import com.kg.component.office.ExcelWriteUtils;
import com.kg.component.utils.GuidUtils;
import com.kg.core.exception.BaseException;
import com.kg.core.retgister.dto.RegisterFormDTO;
import com.kg.module.jtnc.constant.RoleConstant;
import com.kg.module.jtnc.hhrdagl.dto.KrHhrdaglDTO;
import com.kg.module.jtnc.hhrdagl.dto.convert.KrHhrdaglConvert;
import com.kg.module.jtnc.hhrdagl.entity.KrHhrdagl;
import com.kg.module.jtnc.hhrdagl.excels.KrHhrdaglExcelConstant;
import com.kg.module.jtnc.hhrdagl.excels.KrHhrdaglExcelOutDTO;
import com.kg.module.jtnc.hhrdagl.mapper.KrHhrdaglMapper;
import com.kg.module.jtnc.util.Incremental;
import com.kg.module.jtnc.util.PublicUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 合伙人档案管理表 服务实现类
 * </p>
 *
 * @author xxx
 * @since 2024-11-02
 */
@Service
public class KrHhrdaglServiceImpl extends ServiceImpl<KrHhrdaglMapper, KrHhrdagl> implements KrHhrdaglService {

    @Resource
    private KrHhrdaglConvert krHhrdaglConvert;
    @Resource
    private KrHhrdaglMapper krHhrdaglMapper;


    /**
     * 分页列表
     *
     * @param page   页码
     * @param limit  条数
     * @param params 查询条件
     * @return 分页列表
     */
    @Override
    public Page<KrHhrdaglDTO> pagelist(Integer page, Integer limit, String params) {
        // 解析查询参数
        JSONObject paramObj = new JSONObject();
        if (StringUtils.hasText(params)) {
            paramObj = JSONUtil.parseObj(params);
        }
        // 计算分页偏移量
        Integer offset = (page - 1) * limit;
        paramObj.set("limit", limit);
        paramObj.set("offset", offset);
        // 查询列表
        List<KrHhrdaglDTO> list = krHhrdaglMapper.list(paramObj);
        Page<KrHhrdaglDTO> result = new Page<>();
        result.setRecords(list);
        result.setTotal(krHhrdaglMapper.count(paramObj));// 查询总数
        return result;
    }

    /**
     * 新增
     *
     * @param krHhrdaglDTO 新增实体
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void add(KrHhrdaglDTO krHhrdaglDTO) throws BaseException {
        KrHhrdagl krHhrdagl = krHhrdaglConvert.dtoToEntity(krHhrdaglDTO);
        krHhrdagl.setHhrId(GuidUtils.getUuid());
        krHhrdagl.setHhrUserId(krHhrdagl.getHhrId());
        krHhrdagl.setCreateTime(LocalDateTime.now());
        KrHhrdagl one = krHhrdaglMapper.selectOne(new QueryWrapper<KrHhrdagl>().select("max(hhrbh) as hhrbh").last("limit 1"));
//        KrHhrdagl one = lambdaQuery().se("max(hhrbh) as hhrbh").last("limit 1").one();
        if (BeanUtil.isEmpty(one)) {
            krHhrdagl.setHhrbh("HHR"+DateUtil.thisYear() + "0001");
        } else {
            krHhrdagl.setHhrbh(Incremental.increment(one.getHhrbh()));
        }
        RegisterFormDTO registerFormDTO = new RegisterFormDTO();
        registerFormDTO.setNickName(krHhrdagl.getHhrxm());
        registerFormDTO.setUserName(krHhrdagl.getHhrlxfs());
        registerFormDTO.setUserId(krHhrdagl.getHhrId());
        registerFormDTO.setRoleId(RoleConstant.HEHUOREN);
        PublicUtil.registerUser(registerFormDTO);
        save(krHhrdagl);
    }

    /**
     * 修改
     *
     * @param krHhrdaglDTO 编辑实体
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void update(KrHhrdaglDTO krHhrdaglDTO) throws BaseException {
        KrHhrdagl krHhrdagl = krHhrdaglConvert.dtoToEntity(krHhrdaglDTO);
        krHhrdagl.setUpdateTime(LocalDateTime.now());
        RegisterFormDTO registerFormDTO = new RegisterFormDTO();
        registerFormDTO.setNickName(krHhrdagl.getHhrxm());
        registerFormDTO.setUserName(krHhrdagl.getHhrlxfs());
        registerFormDTO.setUserId(krHhrdagl.getHhrId());
        PublicUtil.updateUser(registerFormDTO);
        updateById(krHhrdagl);
    }

    /**
     * 删除
     *
     * @param idlist 删除id列表
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void delete(List<String> idlist) {
        removeBatchByIds(idlist);
        PublicUtil.deleteUser(idlist);
    }

    /**
     * 导出Excel
     *
     * @param params 查询参数
     * @return 导出后的文件url
     */
    @Override
    public String exportExcel(String params) {
        try {
            // 拼接导出Excel的文件，保存的临时路径
            String path = FilePathConfig.SAVE_PATH + "/exportTemp/excel/"
                    + DateUtil.format(new Date(), "yyyyMMdd") + "/" + GuidUtils.getUuid32() + ".xlsx";

            // 查询待导出的数据
            JSONObject paramObj = new JSONObject();
            if (StringUtils.hasText(params)) {
                paramObj = JSONUtil.parseObj(params);
            }

            List<KrHhrdaglDTO> list = krHhrdaglMapper.list(paramObj);
            // 转换成导出excel实体
            List<KrHhrdaglExcelOutDTO> dataList = list.stream()
                    .map(d -> JSONUtil.toBean(JSONUtil.parseObj(d), KrHhrdaglExcelOutDTO.class))
                    .collect(Collectors.toList());
            if (dataList == null || dataList.size() <= 0) {
                // 未查到数据时，模拟一行空数据
                dataList.add(new KrHhrdaglExcelOutDTO());
            }
            // 第一行标题
            String title = "合伙人档案管理表";
            // 写入导出excel文件
            ExcelWriteUtils.write(path, title, dataList, KrHhrdaglExcelConstant.EXPORT_EXCEL_COLUMN);
            // 导出成功，返回导出地址
            return FilePathConfig.switchUrl(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    /**
     * 导入Excel
     *
     * @param request 请求文件
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public String importExcel(HttpServletRequest request) {
        // 1. 读取导入数据
        int startRowIdx = 2;
        List<KrHhrdagl> importData =
                ExcelReadUtils.read(request, 1, startRowIdx, KrHhrdagl.class, KrHhrdaglExcelConstant.IMPORT_EXCEL_COLUMN);
        if (importData == null || importData.isEmpty()) {
            return "Excel文件中没有数据！";
        }
        // 2. 必填字段校验
        String errorMsg = "";
        int currentRowIdx = startRowIdx;
        if (KrHhrdaglExcelConstant.IMPORT_REQUIRED_COLUMN.size() > 0) {
            for (KrHhrdagl entity : importData) {
                currentRowIdx++;
                JSONObject rowData = JSONUtil.parseObj(entity);
                List<String> emptyColName = new ArrayList<>();
                for (Map.Entry<String, String> col : KrHhrdaglExcelConstant.IMPORT_REQUIRED_COLUMN.entrySet()) {
                    if (!StringUtils.hasText(rowData.getStr(col.getKey()))) {
                        emptyColName.add(col.getValue());
                    }
                }
                if (emptyColName.size() > 0) {
                    errorMsg += "第" + currentRowIdx + "行，必填字段[" + String.join(",", emptyColName) + "]不能为空！<br/>";
                }
            }
        }
        if (StringUtils.hasText(errorMsg)) {
            return errorMsg;
        }
        // 3. 保存
        List<KrHhrdagl> saveData = importData.stream().map(o -> {
            o.setHhrId(GuidUtils.getUuid());
            o.setCreateTime(LocalDateTime.now());
            return o;
        }).collect(Collectors.toList());
        krHhrdaglMapper.saveList(saveData);
        return "";// 导入成功，返回空字符串
    }

    /**
     * 下载导入模板
     *
     * @return 模板文件url
     */
    @Override
    public String downloadTemplate() {
        try {
            // 拼接下载Excel模板，保存的临时路径
            String path = FilePathConfig.SAVE_PATH + "/importTemp/excel/"
                    + DateUtil.format(new Date(), "yyyyMMdd") + "/" + GuidUtils.getUuid32() + ".xlsx";
            // 第一行标题
            String title = "合伙人档案管理表-导入模板";
            // 写入模板字段行
            ExcelWriteUtils.writeTemplate(path, title, KrHhrdaglExcelConstant.IMPORT_EXCEL_COLUMN);
            // 生成模板成功，返回模板地址
            return FilePathConfig.switchUrl(path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

}
